package com.dldata.devtools30.controller.api;

import com.dldata.devtools30.entity.DevtApiMainEntity;
import com.dldata.devtools30.entity.DevtApiSubEntity;
import com.dldata.devtools30.entity.DevtApiTypeEntity;
import com.dldata.devtools30.service.api.DevtApiMainEntityService;
import com.dldata.devtools30.service.api.DevtApiSubEntityService;
import com.dldata.devtools30.service.api.DevtApiTypeEntityService;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/DevtApiMainEntityController")
public class DevtApiMainEntityController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    DevtApiTypeEntityService devtApiTypeEntityService;
    @Autowired
    DevtApiMainEntityService devtApiMainEntityService;
    @Autowired
    DevtApiSubEntityService devtApiSubEntityService;
    
    @RequestMapping(value = "/getAllResTreeGrid")
    @ResponseBody
    public Result getAllResTreeGrid(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap model){
        List<Object> dataList = new LinkedList<Object>();
    
        try{
            List<DevtApiTypeEntity> typeEntities=  devtApiTypeEntityService.getAllData();
            for (int i = 0; i < typeEntities.size(); i++) {
                DevtApiTypeEntity devtApiTypeEntity = typeEntities.get(i);
                Map<String,Object> data=new HashMap<>();
                data.put("id",devtApiTypeEntity.getId());
                data.put("mc",devtApiTypeEntity.getMc());
                data.put("xh",devtApiTypeEntity.getXh());
                data.put("dm",devtApiTypeEntity.getDm());
                data.put("bz",devtApiTypeEntity.getBz());
                data.put("flmc",devtApiTypeEntity.getMc());
                data.put("pId","0");
                dataList.add(data);
            }
            
            String condition=request.getParameter("condition");
            condition= StringUtil.isNullOrSpace(condition)?"":condition;
            String flid=request.getParameter("flid");
            List<DevtApiMainEntity> dataList1 = devtApiMainEntityService.findByCondition(condition,flid);
            dataList1=dataList1.stream().sorted(new Comparator<DevtApiMainEntity>() {
                @Override
                public int compare(DevtApiMainEntity o1, DevtApiMainEntity o2) {
                    if (o1.getXh() == null || o2.getXh() == null) {
                        return 0;
                    }
                    return o2.getXh().compareTo(o1.getXh());
                }
            }).collect(Collectors.toList());
            for (DevtApiMainEntity entity:dataList1) {
                Map<String,Object> data=new HashMap<>();
                data.put("id",entity.getId());
                data.put("mc",entity.getMc());
                data.put("xh",entity.getXh());
                data.put("dm",entity.getDm());
                data.put("pym",entity.getPym());
                data.put("bz",entity.getBz());
                data.put("flmc","");
                typeEntities.stream().filter(f->f.getId().equals(entity.getFlid())).forEach(m->{
                    data.put("flmc",m.getMc());
                
                });
                if(entity.getCancel()!=null&&entity.getCancel()){
                    data.put("mc",entity.getMc()+"[已废除]");
                }
                data.put("pId",entity.getFlid());
                dataList.add(data);
            }
            return Result.ok(dataList);
        }catch(Exception ex){
        
            logger.error("【执行"+this.getClass().getName()+".getAll() 方法失败 】异常："+ex.getMessage());
        
            return Result.error("系统错误，请稍候再试");
        }
    }

    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAll(HttpServletRequest request,
                         HttpServletResponse response,
                         ModelMap model) throws IOException {
        List<Object> dataList = new LinkedList<Object>();

        try{
            String condition=request.getParameter("condition");
            condition= StringUtil.isNullOrSpace(condition)?"":condition;
            String flid=request.getParameter("flid");
            List<DevtApiMainEntity> dataList1 = devtApiMainEntityService.findByCondition(condition,flid);
            dataList1=dataList1.stream().sorted(new Comparator<DevtApiMainEntity>() {
                @Override
                public int compare(DevtApiMainEntity o1, DevtApiMainEntity o2) {
                    if (o1.getXh() == null || o2.getXh() == null) {
                        return 0;
                    }
                    return o2.getXh().compareTo(o1.getXh());
                }
            }).collect(Collectors.toList());
           List<DevtApiTypeEntity> typeEntities=  devtApiTypeEntityService.getAllData();
            for (DevtApiMainEntity entity:dataList1) {
                Map<String,Object> data=new HashMap<>();
                data.put("id",entity.getId());
                data.put("mc",entity.getMc());
                data.put("xh",entity.getXh());
                data.put("dm",entity.getDm());
                data.put("pym",entity.getPym());
                data.put("bz",entity.getBz());
                data.put("flmc","");
                typeEntities.stream().filter(f->f.getId().equals(entity.getFlid())).forEach(m->{
                    data.put("flmc",m.getMc());

                });
                if(entity.getCancel()!=null&&entity.getCancel()){
                    data.put("mc",entity.getMc()+"[已废除]");
                }

                dataList.add(data);
            }
            return Result.ok(dataList);
        }catch(Exception ex){

            logger.error("【执行"+this.getClass().getName()+".getAll() 方法失败 】异常："+ex.getMessage());

            return Result.error("系统错误，请稍候再试");
        }

    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap model,DevtApiMainEntity pFunctionmainEntity) throws IOException {
        if(StringUtil.isEmptyOrLength0(pFunctionmainEntity.getMc()) ){
            return Result.error("名称不能为空");
        }
        if(StringUtil.isEmptyOrLength0(pFunctionmainEntity.getDm()) ){
            return Result.error("代码不能为空");
        }
        try {
            if(StringUtil.isNullOrSpace(pFunctionmainEntity.getId())){
                pFunctionmainEntity.setId(UUID.randomUUID().toString());
            }
            pFunctionmainEntity.setPym(StringUtil.getPinYinHeadChar(pFunctionmainEntity.getMc()));
            DevtApiTypeEntity pFunctiontypeEntity = devtApiTypeEntityService.findOne(pFunctionmainEntity.getFlid());
            if(pFunctiontypeEntity!=null&&pFunctiontypeEntity.getCancel()!=null&&pFunctiontypeEntity.getCancel()){
                pFunctiontypeEntity.setCancel(false);
                devtApiTypeEntityService.save(pFunctiontypeEntity);
            }
            devtApiMainEntityService.save(pFunctionmainEntity);

            return Result.ok();
        }catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".save() 方法失败 】异常："+ex.getMessage());
            return Result.error("系统错误，请稍候再试");
        }
    }
    @RequestMapping(value = "/delete")
    @ResponseBody
    public  Result delete(String id,HttpServletRequest request,
                                    HttpServletResponse response)throws Exception{

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            if(devtApiSubEntityService.getAllDataById(id).size()>0){
                return Result.error("该分类下有未删除的api");
            }
            devtApiMainEntityService.delete(id);
            return Result.ok();
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }
    @RequestMapping(value = "/cancel")
    @ResponseBody
    public  Result cancel(String id,HttpServletRequest request,
                                    HttpServletResponse response)throws Exception{

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            DevtApiMainEntity pFunctionmainEntity = devtApiMainEntityService.findOne(id);
            List<DevtApiSubEntity> pFunctionsubEntityList= devtApiSubEntityService.getAllDataById(pFunctionmainEntity.getId());
            if(pFunctionsubEntityList.size()==0&&pFunctionmainEntity.getCancel()!=null&&pFunctionmainEntity.getCancel()){
                devtApiMainEntityService.delete(pFunctionmainEntity.getId());
            }else{
                pFunctionmainEntity.setCancel(true);
                devtApiMainEntityService.save(pFunctionmainEntity);
            }
            return Result.ok();

        }catch (Exception ex){
            ex.printStackTrace();

            logger.error("【执行"+this.getClass().getName()+".deleteKeShi() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试");
        }

    }
}
